
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include "Device.h"
#include "DBHelper.h"
#include "TableSerialized.h"

using namespace std;

namespace Client {
namespace Common {

typedef CTableCached<CDevice> CTableDevice;
typedef CTableSerialized<CDevice> CTableDeviceSerialized;
static string TABLE_NAME = "device";

CDevice::CDevice(CDBCursor& c) : CRecord(c)
{
	c.GetString(1, mId);
	c.GetString(2, mName);
	c.GetInt(3, mType);
}

CDevice::CDevice(JsonValue& v)
{
	SetValue(v["id"], mId);
	SetValue(v["name"], mName);
	SetValue(v["type"], mType);
}

string& CDevice::GetTableName()
{
	return TABLE_NAME;
}

void CDevice::GetValueSet(map<string, string>& values)
{
	values["_id"] = GetValueDesc(mId);
	values["name"] = GetValueDesc(mName);
	values["type"] = GetValueDesc(mType);
}

TableRef CDevice::Query()
{
	return CTableDevice::Query(TABLE_NAME, string(), string());
}

DeviceRef CDevice::Query(string& id)
{
	string s;
	TableRef td = CTableDevice::Query(TABLE_NAME, string("_id=") + CRecord::GetValueDesc(id, s), string());
	DeviceRef dev;
	if(td) {
		if(td->GetCount() > 0) {
			boost::shared_array<RecordRef> recs = td->NextRecords(1);
			if(td->GetCurrentRecordsCount() > 0) {
				dev = boost::dynamic_pointer_cast<CDevice, CRecord>(recs[0]);
			}
		}
		td->Close();
	}

	return dev;
}

void CDevice::WriteJson(JsonWriter& writer)
{	
	writer.StartObject();
	writer.String("id").String(mId.c_str());
	writer.String("name").String(mName.c_str());
	writer.String("type").Int(mType);
	writer.EndObject();

}

bool CDevice::AddDevice(DeviceRef dev)
{
	DeviceRef olddev = Query(dev->mId);
	if(olddev) {
		dev->mIndex = olddev->mIndex;
		return CDBHelper::GetInstance().Update(*dev);
	}
	else {
		return CDBHelper::GetInstance().Insert(*dev);
	}

}

TableRef CDevice::GetSerializedTable(CTable& table)
{
	return CTableDeviceSerialized::Create(table);
}

TableRef CDevice::GetSerializedTable(string& js)
{
	return TableRef(new CTableDeviceSerialized(js));
}

TableRef CDevice::GetSerializedTable()
{
	return TableRef(new CTableDeviceSerialized());
}

} // Common
} // Client